﻿using System;
using System.ComponentModel;
using System.ServiceModel;
using System.Threading;
using Central.Annotations;
using SharedServiceLibrary;

namespace Central
{
    public class PumpStation : INotifyPropertyChanged
    {
        private WaterLevel _waterLevel;
        private Thread _thread;
        private bool _running;

        public IPumpStationService Proxy { get; private set; }
        public int Id { get; set; }
        public string Name { get; set; }
        public string IPAddress { get; set; }
        public int Port { get; set; }
        public object WaterLevel
        {
            get
            {
                var waterLevels = new[] {"Lav", "Normal", "Høj", "Kritisk"};
                return waterLevels.Length > (int) _waterLevel ? waterLevels[(int) _waterLevel] : "Ukendt";
            }
            set
            {
                if (Equals(value, _waterLevel)) return;
                _waterLevel = (WaterLevel) value;
                OnPropertyChanged("WaterLevel");
            }
        }

        public PumpStation(int id, string name, string ipAddress, int port)
        {
            Id = id;
            Name = name;
            IPAddress = ipAddress;
            Port = port;

            Proxy = new ChannelFactory<IPumpStationService>(new NetTcpBinding(), "net.tcp://" + ipAddress + ":" + port).CreateChannel();
            WaterLevel = 5;
            //WaterLevel = Proxy.GetWaterLevel();

            Start();
        }

        private void Start()
        {
            _running = true;
            _thread = new Thread(Run);
            _thread.Start();
        }

        public void Stop()
        {
            _running = false;
            _thread.Join();
        }

        private void Run()
        {
            while (_running)
            {
                try
                {
                    WaterLevel = Proxy.GetWaterLevel();
                    Thread.Sleep(1000);
                }
                catch
                {
                    _running = false;
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}